package com.cmq.web_1.employeemanage;


import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "AuthenticationFilter", urlPatterns = {"/employeemanage/dashboard", "/employeemanage/*"})
public class AuthenticationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化操作
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);

        // 检查用户是否已登录
        boolean isLoggedIn = (session != null && session.getAttribute("user") != null);

        // 登录页面不需要过滤
        String loginURI = httpRequest.getContextPath() + "/employeemanage/login";

        boolean isLoginRequest = httpRequest.getRequestURI().equals(loginURI);
        boolean isLoginPage = httpRequest.getRequestURI().endsWith("/employeemanage/login.jsp");

        if (isLoggedIn && (isLoginRequest || isLoginPage)) {
            // 如果已登录，重定向到仪表盘
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/employeemanage//dashboard");
        } else if (isLoggedIn || isLoginRequest || isLoginPage) {
            // 已登录或访问登录页面，继续处理
            chain.doFilter(request, response);
        } else {
            // 未登录且访问受保护资源，重定向到登录页面
            httpResponse.sendRedirect(loginURI);
        }
    }

    @Override
    public void destroy() {
        // 销毁操作
    }
}